package org.unidata.mdm.search.type.query;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import org.apache.commons.collections4.CollectionUtils;
import org.unidata.mdm.search.type.form.FieldsGroup;

/**
 * @author Mikhail Mikhailov on Feb 20, 2020
 */
public class FormSearchQuery implements SearchQuery {
    /**
     * Form groups.
     */
    private final List<FieldsGroup> groups;
    /**
     * Constructor.
     * @param groups the groups
     */
    protected FormSearchQuery(List<FieldsGroup> groups) {
        super();
        this.groups = groups;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public SearchQueryType getType() {
        return SearchQueryType.FORM;
    }
    /**
     * Telld, whether it is empty.
     * @return true, if empty, false otherwise
     */
    public boolean isEmpty() {
        return CollectionUtils.isEmpty(groups);
    }
    /**
     * @return the groups
     */
    public List<FieldsGroup> getGroups() {
        return CollectionUtils.isEmpty(groups) ? Collections.emptyList() : groups;
    }
    /**
     * Joins two FSQs by merging AND groups to a single one and just adding other groups to list.
     * @param other the other query
     */
    public void join(FormSearchQuery other) {

        if (Objects.isNull(other) || other.isEmpty()) {
            return;
        }
        /*
        FormFieldsGroup thisAnd = null;
        for (FormFieldsGroup group : getGroups()) {
            if (group.getGroupType() == GroupType.AND) {
                thisAnd = group;
                break;
            }
        }

        FormFieldsGroup othersAnd = null;
        List<FormFieldsGroup> othersGroups = new ArrayList<>(other.getGroups().size());
        for (FormFieldsGroup group : other.getGroups()) {
            // AND
            if (group.getGroupType() == GroupType.AND) {
                othersAnd = group;
            // OR
            } else {
                othersGroups.add(group);
            }
        }

        if (Objects.nonNull(thisAnd) && Objects.nonNull(othersAnd)) {
            thisAnd.addAll(othersAnd.getFormFields());
            thisAnd.addAllGroups(othersAnd.getChildGroups());
        } else if (Objects.isNull(thisAnd) && Objects.nonNull(othersAnd)) {
            groups.add(0, othersAnd);
        }
        */
        groups.addAll(other.getGroups());
    }
}
